<template>
	<view>
		<!-- 普通商城商品规格 -->
		<u-popup :show="show" :round="10" mode="bottom" v-if="type == 1">
			<view class="pwd-popup pr text-black3">
				<u-icon name="close" size="24" @click="close" class="close-icon" />
				<view class="flex align-center p-t-20">
					<view>
						<image :src="skuData.mainImageUrl" class="img-168 radius-8" />
					</view>
					<view class="margin-left">
						<view class="font-13 text-bold text-cut2">{{skuData.productName}}</view>
						<view class="m-t-5">
							<text class="font-20 text-theme text-bold">¥{{skuData.productPrice}}</text>
							<text class="font-13 text-gray margin-left-sm noUse">¥{{ skuData.priceScribing }}</text>
						</view>
						<view class="m-t-5">
								<text class="font-12 text-gray">规格: {{ skuData.specValue }}</text>
						</view>
					</view>
				</view>
				<view v-for="(spec,index) in skuData.skuSpec" :key="index">
					<view class="font-15 text-bold m-t-15 m-b-15">{{ spec.specName }}</view>
					<view class="flex justify-between flex-wrap maxHeight">
						<view v-for="(specItem,indexs) in spec.specValue" :key="indexs" :class="specItem.isActive?'specActive specBox':'specBox'" @click="selectSpec(specItem,spec)">{{ specItem.value }}</view>
					</view>
				</view>
			<!-- 	<view class="font-15 text-bold m-t-15 m-b-15">规格</view>
				<view class="flex justify-between flex-wrap maxHeight">
					<view class="sku-item" :class="{'sku-item-active': item.publishStatus == 1&&skuIndex == index}" v-for="(item, index) in detail.skuList" :key="index" @click="selectSku(item,index)" :style="{color: (item.inventory <= 0 ? '#cccccc':'#000000'),background: item.publishStatus == 2? '#e5e5e5':''}" >{{ item.specValue }}</view>
				</view> -->
				<view class="flex justify-between font-15 text-bold m-t-15 m-b-20">
					<view>数量:</view>
					<view>
						<u-number-box v-model="stepVal" min="1"></u-number-box>
					</view>
				</view>

				<view class="flex justify-between align-center">
					<view>
						<view>
							<text class="font-15 text-bold">总计：</text>
							<text class="text-theme font-20 text-bold">¥{{skuData.productPrice | totalNum(stepVal) }}</text>
						</view>
						<view class="font-13 text-gray p-l-45 noUse">¥{{ skuData.priceScribing | totalNum(stepVal)  }}</view>
					</view>
					<view class="bottomBtn" @tap="submit">{{ skuData.noGoods ? "库存不足":'立即购买'}}</view>
				</view>
			</view>
		</u-popup>
		<!-- 积分商城商品规格 -->
		<u-popup :show="show" :round="10" mode="bottom" v-if="type == 2">
			<view class="pwd-popup pr text-black3">
				<u-icon name="close" size="24" @click="close" class="close-icon" />
				<view class="flex align-center p-t-20">
					<view>
						<image :src="skuData.mainImageUrl" class="img-168 radius-8" />
					</view>
					<view class="margin-left">
						<view class="font-13 text-bold text-cut2">{{skuData.productName}}</view>
						<view class="m-t-5">
							<text class="font-20 text-theme text-bold">¥{{skuData.productPrice}}</text>
							<text class="font-13 text-gray margin-left-sm noUse">¥{{ skuData.priceScribing }}</text>
						</view>
						<view class="m-t-5">
								<text class="font-12 text-gray">规格: {{ skuData.specValue }}</text>
						</view>
					</view>
				</view>
				<view v-for="(spec,index) in skuData.skuSpec" :key="index">
					<view class="font-15 text-bold m-t-15 m-b-15">{{ spec.specName }}</view>
					<view class="flex justify-between flex-wrap maxHeight">
						<view v-for="(specItem,indexs) in spec.specValue" :key="indexs" :class="specItem.isActive?'specActive specBox':'specBox'" @click="selectSpec(specItem,spec)">{{ specItem.value }}</view>
					</view>
				</view>
<!-- 				<view class="font-15 text-bold m-t-15 m-b-15">规格</view>
				<view class="flex justify-between flex-wrap">
					<view class="sku-item" :class="{'sku-item-active': skuIndex == index}" v-for="(item, index) in detail.skuList" :key="index" @click="selectSku(item,index)" :style="{color: (item.inventory <= 0 ? '#cccccc':'#000000'), background: item.publishStatus == 2? '#cccccc':''}" >{{ item.specValue }}</view>
				</view> -->
				<view class="flex justify-between font-15 text-bold m-t-15 m-b-20">
					<view>数量</view>
					<view>
						<u-number-box v-model="stepVal" min="1"></u-number-box>
					</view>
				</view>

				<view class="flex justify-between align-center">
					<view>
						<view>
							<text class="font-15 text-bold">总计：</text>
							<text class="text-theme font-20 text-bold">¥{{skuData.productPrice | totalNum(stepVal) }}</text>
						</view>
						<view class="font-13 text-gray p-l-45 noUse">¥{{ skuData.priceScribing | totalNum(stepVal)  }}</view>
					</view>
					<view class="bottomBtn" @tap="submit">{{ skuData.noGoods ? "库存不足":'立即兑换'}}</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	// import { orderCreate } from '@/common/api/order.js';
	export default {
		data() {
			return {
				stepVal: 1,
				skuIndex: 0,
				skuData: {},
				nowSkuData:{},
			};
		},
		props: {
			detail: {
				type: Object,
				default: () => {}
			},
			show: {
				type: Boolean,
				default: false
			},
			// type 1 普通商品规格
			// type 2 积分商城商品规格
			type: {
				type: Number,
				default: 1
			}
		},
		watch: {
			show: {
				handler(val) {
					if(val) {
						this.skuData = JSON.parse(JSON.stringify(this.detail));
						// 组装规格数据,给skuData数据新增attributesArr
						let specAllVal = [];
						// publishStatus == 2 代表已经下架了 ，要过滤掉,以免后面显示处理不对
						this.skuData.skuList = this.skuData.skuList.filter(item => {
							return item.publishStatus != 2
						})
						this.skuData.skuList.forEach(item => {
							if(item.attributes.length && item.publishStatus != 2){
								item.attributes.forEach(attr => {
									specAllVal.push(attr)
								})
							}
						})
						this.processData = this.getProcessData(specAllVal)
						this.skuData.skuList.forEach(item => {
							let arr = [];
							if(item.attributes.length){
								item.attributes.forEach(attr => {
									arr.push(attr.values[0])
								})
							}
							item['attributesArr'] = arr
						})
						this.skuData.skuSpec = this.processData; //位置不能改，只能在这里
						// 如果没有缓存高亮商品，默认高亮第一个sku商品的规格
						if(!uni.getStorageSync('haveSpec')){
							this.nowSkuData = this.skuData.skuList[0];
							this.skuData.skuList[0].attributes.forEach(item => {
								console.log(item,"item======")
								console.log(this.processData,"this.processData=========")
								this.processData.forEach(pro => {
									// 规格名相同,则高亮显示该规格下和sku的规格相同值的数据
									if(item.name == pro.specName){
										pro.specValue.forEach(vals => {
											if(vals.value === item.values[0]){
												vals.isActive = true
											}else{
												vals.isActive = false
											}
										})
									}
								})
							})
						}else{ //如果有缓存，则高亮缓存数据
							let arr = uni.getStorageSync('haveSpec')
							console.log("有有有有有有有有有有缓存",JSON.parse(JSON.stringify(arr)))
							this.skuData.skuList.forEach(item => {
								let bool = this.checkArrayIsSame(item.attributesArr,arr)
								// 获取当前高亮展示的是哪一个
								if(item.attributes.length && bool){
									this.nowSkuData = item
								}
							})
							// 高亮显示所选规格
							this.processData.forEach(pro => {
								if(pro.specValue.length){
									pro.specValue.forEach(vals => {
										if(arr.indexOf(vals.value) !== -1){
											vals.isActive = true
										}else{
											vals.isActive = false
										}
									})
								}
							})
						}
						this.displayGoods()//展示sku商品
						this.$forceUpdate()
					}
				},
				immediate: true,
				deep: true
			}
		},

		filters: {
			totalNum: function(num,val) {
				if(!num) return 0
				if(!val) return 0
				return (num * val).toFixed(2)
			}
		},
		methods: {
			// 选择规格
			selectSpec(data,spec){
				this.nowSkuData = {}
				this.processData.forEach(item => {
					if(item.specName == spec.specName && item.specValue.length > 0){
						item.specValue.forEach(itemSpec => {
							if(itemSpec.value == data.value && !data.isActive){
								itemSpec.isActive = true
							}else if(itemSpec.value == data.value && data.isActive){
								itemSpec.isActive = true
							}else{
								itemSpec.isActive = false
							}
						})
					}
				})
				this.skuData.skuSpec = this.processData
				this.$forceUpdate()
				
				// 匹配sku数据
				let arr = [];//当前高亮规格值
				this.processData.forEach(item => {
					if(item.specValue.length){
						item.specValue.forEach(val => {
							if(val.isActive){
								arr.push(val.value)
							}
						})
					}
				})
				// 找到当前匹配sku数据
				this.skuData.skuList.forEach(item => {
					let bool = this.checkArrayIsSame(arr,item.attributesArr)
					if(bool){
						this.nowSkuData = item
					}
				})
				uni.setStorageSync('haveSpec',arr)
				this.displayGoods()
			},
			// 处理当前展示数据
			displayGoods(){// 没有该规格的商品默认展示第一个sku商品数据，只是提示库存不足，不能下单(下单就提示库存不足)
				if(JSON.stringify(this.nowSkuData) == '{}'){
					uni.showToast({
							title: '该商品规格库存不足',
							icon: 'none'
					})
					// 将当前数据默认
					this.nowSkuData = this.skuData.skuList[0]
					
					this.skuData.productPrice = this.nowSkuData.platformPrice
					this.skuData.costPrice = this.nowSkuData.costPrice
					this.skuData.mainImageUrl = this.nowSkuData.pic
					this.skuData.id = this.nowSkuData.id
					this.skuData.priceScribing = this.nowSkuData.crossedPrice
					this.skuData.specValue = this.nowSkuData.specValue
					this.skuData.productName = this.nowSkuData.skuName
					this.skuData.contributionValue = this.nowSkuData.contributionValue
					this.skuData.giftValue = this.nowSkuData.giftValue
					this.skuData.noGoods = true
				}else{// 展示高亮选择的sku商品数据
					this.skuData.productPrice = this.nowSkuData.platformPrice
					this.skuData.costPrice = this.nowSkuData.costPrice
					this.skuData.mainImageUrl = this.nowSkuData.pic
					this.skuData.id = this.nowSkuData.id
					this.skuData.priceScribing = this.nowSkuData.crossedPrice
					this.skuData.specValue = this.nowSkuData.specValue
					this.skuData.productName = this.nowSkuData.skuName
					this.skuData.contributionValue = this.nowSkuData.contributionValue
					this.skuData.giftValue = this.nowSkuData.giftValue
					this.skuData.noGoods = false
				}
			},
			// 判断两个数组元素是否都一样
			checkArrayIsSame(listA,listB){
				let flag = true
				if (listA.length !== listB.length) {
					flag = false
				} else {
					listA.forEach(item => {
						if (listB.indexOf(item) === -1) {
							flag = false
						}
					})
				}
				return flag;
			},
			// 规格数据
			getProcessData(inputData) {
				let outputData = [];
				
				// 创建一个对象来存储每个规格名称对应的规格值
				let specMap = {};

				// 遍历输入数据
				inputData.forEach(item => {
						let specName = item.name; // 规格名称
						let specValue = item.values[0]; // 规格值

						// 如果规格名称不存在于specMap中，则将规格名称和对应的规格值加入到specMap中
						if (!specMap[specName]) {
								specMap[specName] = [];
						}
						// 如果规格值不在已有的规格值列表中，则将其添加到列表中
						if (!specMap[specName].find(value => value.value === specValue)) {
								specMap[specName].push({ value: specValue, isActive: false });
						}
				});

				// 将specMap中的数据转换为所需的输出格式
				for (const [specName, specValues] of Object.entries(specMap)) {
						outputData.push({
								"specName": specName,
								"specValue": specValues,
						});
				}

				return outputData;
			},
			// // 创建订单
			// orderCreate(){
			// 	let parmas = {
			// 		skuId : this.skuData.id,
			// 		buyCount: this.stepVal,
			// 		remark : "",
			// 	}
			// 	orderCreate(parmas).then(res => {
			// 		if(res.code == 200) {
			// 			uni.navigateTo({
			// 				url: '/pages/order/pay/payOrder?orderno='+ res.data
			// 			})
			// 		}
			// 	})
			// },
			selectSku(item,index) {
				if(item.publishStatus == 2) {
						uni.showToast({
								title: '该规格已下架',
								icon: 'none'
						})
						return
				}

				if(item.inventory <= 0) {
					uni.showToast({
						title: '库存不足',
						icon: 'none'
					})
					return
				}
				
				this.skuIndex = index
				this.skuData.productPrice = item.platformPrice
				this.skuData.costPrice = item.costPrice
				this.skuData.mainImageUrl = item.pic
				this.skuData.id = item.id
				this.skuData.priceScribing = item.crossedPrice
				this.skuData.specValue = item.specValue
				this.skuData.productName = item.skuName
				this.skuData.contributionValue = item.contributionValue
				this.skuData.productArea = this.detail.productArea
				this.skuData.giftValue = item.giftValue
			},
			submit() {
				// type 1 普通商品规格
				// type 2 积分商城商品规格
				
				// 如果选到没有该规格的商品
				if(this.skuData.noGoods){
						uni.showToast({
								title: '该商品规格库存不足',
								icon: 'none'
						})
						return
				}
				
				//publishStatus: 1 上架  2 下架
				if(this.skuData?.publishStatus == 2) {
						uni.showToast({
								title: '该商品规格已下架',
								icon: 'none'
						})
						return
				}


				if(this.type == 1) {
					uni.setStorageSync('skuData', this.skuData)
					uni.navigateTo({
						url: '/pages/order/placeOrder?num='+this.stepVal
					})
				}else {
					uni.setStorageSync('skuData', this.skuData)
					uni.navigateTo({
						url: '/pages/points/placeOrder?num='+this.stepVal
					})
				}
			},
			close() {
				this.$emit('close')
			},
		}
	}
</script>

<style lang="scss" scoped>
.specBox{
	min-width: calc(50% - 15rpx);
	min-height: 64rpx;
	border-radius: 8rpx;
	border: 1rpx solid #999999;
	font-size: 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-bottom: 30rpx;
	padding: 0 30rpx;
	box-sizing: border-box;
}
.specActive{
	color: #FA3121;
	border: 1px solid #FA3121;
	background: #fff6f5;
}
.maxHeight{
	max-height: 400rpx;
	overflow-y: scroll;
}
.pwd-popup {
	border-radius: 40rpx;
	padding: 40rpx;

	.close-icon {
		position: absolute;
		top: 30rpx;
		right: 30rpx;
	}

	.bottomBtn {
		width: 328rpx;
		height: 88rpx;
		background: linear-gradient(42deg, #FF0804 0%, #FC7844 100%);
		box-shadow: 0rpx 2rpx 10rpx 1rpx rgba(250,49,33,0.24);
		border-radius: 16rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		color: #ffffff;
	}
	.sku-item {
		min-width: calc(50% - 15rpx);
		min-height: 64rpx;
		border-radius: 8rpx;
		border: 1rpx solid #999999;
		font-size: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 30rpx;
		padding: 0 30rpx;
	}
	.sku-item-active {
		color: #FA3121;
		border: 1px solid #FA3121;
		background: #fff6f5;
	}
}
</style>
